import xml.dom.minidom
from dicttoxml import dicttoxml
from datetime import datetime
import json
import os
import sqlite3

class log_xml:

    def log(name, pid,opera,student_name):
        opera_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_file = {"姓名": name, "工号": pid,
                    "操作": opera + student_name + "的学生信息", "时间": opera_time}
        xml_data = dicttoxml(log_file)
        dom = xml.dom.minidom.parseString(xml_data)
        xml_str = dom.toprettyxml(indent="  ")
        try:
            with open('图形界面作业/log.xml', 'a', encoding='utf-8') as f:
                f.write(xml_str)
        except FileNotFoundError:
            with open('图形界面作业/log.xml', 'w', encoding='utf-8') as f:
                f.write(xml_str)
                
class log_json:
    def log(name, pid, opera,student_name):
        opera_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_file_path = '图形界面作业/log.json'
        log_entry = {
            "姓名": name,
            "工号": pid,
            "操作": f"{opera}{student_name}的宿舍",
            "时间": opera_time
        }

        if os.path.exists(log_file_path):
            try:
                with open(log_file_path, 'r', encoding='utf-8') as f:
                    existing_logs = json.load(f)
            except json.JSONDecodeError:
                existing_logs = []
            existing_logs.append(log_entry)
            with open(log_file_path, 'w', encoding='utf-8') as f:
                json.dump(existing_logs, f, ensure_ascii=False, indent=4)
        else:
            with open(log_file_path, 'w', encoding='utf-8') as f:
                json.dump([log_entry], f, ensure_ascii=False, indent=4)


class log_db:
    def log(name, pid, opera, student_id):
        opera_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        try:
            conn = sqlite3.connect('student_management.db')
            cursor = conn.cursor()
            cursor.execute('''
                INSERT INTO operation_log (operator_name, operator_id, operation, student_id, operation_time)
                VALUES (?, ?, ?, ?, ?)
            ''', (name, pid, opera, student_id, opera_time))
            conn.commit()
            conn.close()
        except Exception as e:
            print(f"日志保存到数据库失败: {e}")